package com.ocom.oauth.controller;


import com.ocom.common.resp.Result;
import com.ocom.common.utils.CodeUtil;
import com.ocom.common.utils.RequestUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.oauth.client.CompanyClientService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/LoginPage")
@RestController
public class CodeController {


    Logger logger= LoggerFactory.getLogger(CodeController.class);

    @Autowired
    CompanyClientService companyClientService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/verify")
    public Result verifyCode() throws Exception {
        // 记录debug级别的信息
        logger.debug("This is debug message.");
        // 记录info级别的信息
        logger.info("This is info message.");
        // 记录error级别的信息
        logger.error("This is error message.");

        InetAddress ip4 = Inet4Address.getLocalHost();
        Map<String, String> res=getImg(ip4.getHostAddress());
        return ResultUtil.success(res);
    }


    public static void main(String[] args){

        String url="https://api.weixin.qq.com/sns/jscode2session?appid=wx6b177fb8a270765f&secret=74bed8974f4927c84cc4fd1812b9120f&js_code=0619Dj0w3pcRIX2dsS0w3OfmPg29Dj06&grant_type=authorization_code";
        RequestUtil requestUtil=new RequestUtil();
        Map<String,String> map =requestUtil.doGetRequest(url);
        for (Map.Entry<String,String> entry:map.entrySet()){
        }
    }






    /**
     * 生成验证码的base64图片
     * 生成的验证码放入redis
     * @return map中有验证码的id 和图片base64
     * @param id
     */
    public  Map<String, String> getImg(String id) throws Exception {
        Map<String, String> res = new HashMap<>(2);
        //创建文件输出流对象
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Map<String, Object> map = CodeUtil.generateCodeAndPic();
        ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", outputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(outputStream.toByteArray());
        res.put("verify", "data:image/png;base64," + text);
    //    res.put("imgId", id);
    //    System.out.println(String.valueOf(map.get("code")));
     //   res.put("code", String.valueOf(map.get("code")));

        redisUtil.set("verification:"  + String.valueOf(map.get("code")),String.valueOf(map.get("code")),6000L);
        return res;
    }




}
